var express = require('express');
var fs = require('fs');
var router = express.Router();
var multer = require('multer');
var upload = multer({
  dest: 'upload_tmp/'
});
var child_process = require("child_process");
const request = require('request')
var UUID = require('uuid');
var mysql = require('mysql');
/* GET home page. */

/****************************************************页面部分************************************************************* */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});

router.get('/fileList', function (req, res, next) {
  res.render('fileList');
});

router.get('/user', function (req, res, next) {
  res.render('user');
});

router.get('/update', function (req, res, next) {
  res.sendFile(__dirname + '/ind.html')
});

router.get('/updatePass', function (req, res, next) {
  res.sendFile(__dirname + '/password.html')
});

router.get('/login', function (req, res, next) {
  res.render('login');
});

/**
 * 注册用户
 */
router.get('/reg', function (req, res, next) {
  res.sendFile(__dirname + '/reg.html')
});
/****************************************************页面部分************************************************************* */

/****************************************************gitee部分************************************************************* */
/**
 * 新增网盘文件
 */
router.post('/addFile', upload.any(), function (req, res, next) {
  console.log(req.files[0]); // 上传的文件信息
  let token = req.body.token;
  let branch = req.body.branch;
  let owner = req.body.owner;
  let repo = req.body.repo;
  var chunks = [];
  var size = 0;
  var des_file = "./upload/" + req.files[0].originalname;



  fs.readFile(req.files[0].path, function (err, data) {
    chunks.push(data);
    size += data.length;
    var data = Buffer.concat(chunks, size); //Buffer.concat将chunks数组中的缓冲数据拼接起来，返回一个新的Buffer对象赋值给data
    var base64Img = data.toString('base64'); //将Buffer对象转换为字符串并以base64编码格式显示
    uploadFile(req, base64Img,branch,owner,repo).then(data => {
      console.log(data); // 对请求结果进行业务处理
      res.send(data);
    }).catch(ex => {
      console.log(ex); // 此处可处理错误信息
      res.send(data);
    }).finally(() => {
      console.log('finally'); // 进行最后的处理
    });
  });
});

/**
 * 删除文件
 */
router.post('/delFile', (req, res) => {
  debugger
  console.log(req.body.path);
  let path = req.body.path;
  let sha = req.body.sha;
  let master = req.body.master;
  delFileObj(req,path, sha, master).then(data => {
    console.log(data); // 对请求结果进行业务处理
    res.send(data);
  }).catch(ex => {
    console.log(ex); // 此处可处理错误信息
  }).finally(() => {
    console.log('finally'); // 进行最后的处理
  });
})

/**
 * 获取文件树
 */
router.post('/getFileTree', (req, res) => {
  let token = req.body.token;
  let branch = req.body.branch;
  let owner = req.body.owner;
  let repo = req.body.repo;
  getFileTreeObj(token,branch,owner,repo).then(data => {
    console.log(data); // 对请求结果进行业务处理
    res.send(data);
  }).catch(ex => {
    console.log('catch'); // 此处可处理错误信息
    res.send(ex);
  }).finally((ex) => {
    console.log('finally'); // 进行最后的处理
    res.send(ex);
  });

})
/****************************************************gitee部分************************************************************* */

/****************************************************业务逻辑信息************************************************************* */

/**
 * 修改用户信息
 */
router.post('/updateUserInfo', (req, res) => {
  let email = req.body.email;
  let password = req.body.password;
  let token = req.body.token;
  let branch = req.body.branch;
  let owner = req.body.owner;
  let repo = req.body.repo;
  let sql = "UPDATE `user` SET ";
  let sqlparam = [];
  if (password) {
    sqlparam.push(password);
    sql += ",`password` = ? ";
  }
  if (token) {
    sqlparam.push(token);
    sql += ",`token` = ? ";
  }
  if (branch) {
    sqlparam.push(branch);
    sql += ",`branch` = ? ";
  }
  if (owner) {
    sqlparam.push(owner);
    sql += ",`owner` = ? ";
  }
  if (repo) {
    sqlparam.push(repo);
    sql += ",`repo` = ? ";
  }
  sql += " WHERE `email` = ?";
  sqlparam.push(email);
  sql = 'UPDATE `user` SET ' + sql.split('UPDATE `user` SET ')[1].substr(1);
  data(sql, sqlparam, function (err, results) {
    if (err) {
      throw err;
      res.json(err);
    }
    if (results) {
      res.status(200);
      res.send(results);
    }
  })
})

router.post('/updatePassInfo', (req, res) => {
  res.send('你好');
})

// 新增用户
router.post('/addUserInfo', (req, res) => {
  let email = req.body.email;
  let password = req.body.password;
  let sql = "INSERT INTO `user`( `email`, `password`, `create_time`) VALUES (?, ?, now());";
  let sqlparam = [];
  sqlparam.push(email);
  sqlparam.push(password);
  data(sql, sqlparam, function (err, results) {
    if (err) {
      throw err;
      res.json(err);
    }
    if (results) {
      res.status(200);
      res.send(results);
    }
  })
})

router.post('/loginUser', (req, res) => {
  let email = req.body.email;
  let password = req.body.password;
  data('SELECT * FROM user where email=? and password=?', [email, password], function (err, results) {
    if (err) {
      throw err;
      res.json(err);
    }
    if (results) {
      res.status(200);
      res.send(results);
    }
  })
})

/****************************************************业务逻辑信息************************************************************* */

/****************************************************公共方法部分************************************************************* */


function uploadFile(req, base64Img,branch,owner,repo) {
  const extname = (filename) => {
    if (!filename || typeof filename != 'string') {
      return false
    };
    let a = filename.split('').reverse().join('');
    let b = a.substring(0, a.search(/\./)).split('').reverse().join('');
    return b
  }
  let token = req.body.token;
  return new Promise((resolve, reject) => {
    request.post('https://gitee.com/api/v5/repos/'+owner+'/'+repo+'/contents/' + UUID.v1() + '.' + extname(encodeURI(req.files[0].originalname)) + '', {
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
      },
      form: {
        access_token: token,
        content: base64Img,
        message: req.files[0].originalname,
        branch:branch?branch:'master'
      },
    }, (err, res, body) => {
      console.log(body)
      fs.unlinkSync(req.files[0].path, function (err) {
        if (err) throw err;
        reject(err)
      });
      resolve(body);
    })
  })
}


/**
 * 获取文件树
 * @returns 
 */
function getFileTreeObj(token,branch,owner,repo) {
  branch = branch?branch:'master';
  let url = "https://gitee.com/api/v5/repos/"+owner+"/"+repo+"/git/trees/"+branch+"?access_token="+token+"&recursive=1";
  return new Promise((resolve, reject) => {
    request.get(url, {
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
      }
    }, function (err, httpResponse, body) {
      if (err) {
        reject(err)
      } else {
        resolve(body)
      }
    })
  })
}

function delFileObj(req,path, sha, master) {
  debugger
  let token = req.body.token;
  let owner = req.body.owner;
  let repo = req.body.repo;
  return new Promise((resolve, reject) => {
    request.delete("https://gitee.com/api/v5/repos/"+owner+"/"+repo+"/contents/" + path + "?access_token="+token+"&sha=" + sha + "&message=%E5%88%A0%E9%99%A4&branch=" + master + "", {
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
      }
    }, function (err, httpResponse, body) {
      if (err) {
        reject(err)
      } else {
        resolve(body)
      }
    })
  })
}


function data(sql, sdata, callback, add = null) {
  let host = {
    host: '47.98.190.92',
    user: 'pan',
    password: 'F72wAScCWP8rj6CD',
    database: 'pan'
  };

  var connection = mysql.createConnection(host);
  connection.connect();
  //增删改查
  if (add != null) {
    connection.query(sql, sdata, add, callback);
  } else {
    connection.query(sql, sdata, callback);
  }
  connection.end();
}



/****************************************************公共方法部分************************************************************* */

module.exports = router;